package com.azxc.rapid.auth.granter;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.azxc.rapid.auth.constant.AuthConstant;
import com.azxc.rapid.auth.jianguan.SuperviseAuthenticationToken;
import com.azxc.rapid.auth.service.RapidUserDetails;
import com.azxc.rapid.auth.utils.TokenUtil;
import com.azxc.rapid.core.redis.cache.RapidRedis;
import com.azxc.rapid.core.tool.api.R;
import com.azxc.rapid.core.tool.support.Kv;
import com.azxc.rapid.core.tool.utils.BeanUtil;
import com.azxc.rapid.core.tool.utils.Func;
import com.azxc.rapid.core.tool.utils.StringUtil;
import com.azxc.rapid.core.tool.utils.WebUtil;
import com.azxc.rapid.system.user.entity.User;
import com.azxc.rapid.system.user.entity.UserInfo;
import com.azxc.rapid.system.user.entity.UserOauth;
import com.azxc.rapid.system.user.feign.IUserClient;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author linym
 * @className: WestoneGranter
 * @description:
 * @date 2023/1/16 10:05
 * @version：1.0
 */
public class WestoneGranter extends AbstractTokenGranter {
	private static final String GRANT_TYPE = "westone";
	private final IUserClient userClient;

	private final String appKey;
	private final String corpId;

	private final String corpSecret;


	private RapidRedis rapidRedis;

	/*App Key：APPAD3BADB33B0622F1BE4C0E5A

	App Secret：0oRkwKpQn62jGsTT_cgK5C8a4p0bfiJ49_hsYqrJ49JN4z8q4U_J4Trf8dOu6N0dQU4

	Corp Secret：a1024mo37JlrK3u2_MR7yNv8rKXsGD819_sNsrJZ4Ubg0zSi5y_0k568xPRQ7TIe951*/

	protected WestoneGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, IUserClient userClient,
							 String appKey,String corpId,String corpSecret) {
		super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
		this.userClient = userClient;
		this.appKey = appKey;
		this.corpId = corpId;
		this.corpSecret = corpSecret;
	}



	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		HttpServletRequest request = WebUtil.getRequest();


		Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
		String oauth_code = parameters.get("oauthCode");
		if(StringUtil.isEmpty(oauth_code)){
			throw new InvalidGrantException("缺少参数oauth_code！");

		}
		String tenantId = Func.toStr(request.getHeader(TokenUtil.TENANT_HEADER_KEY), TokenUtil.DEFAULT_TENANT_ID);

		RapidUserDetails rapidUserDetails;
		String tele = "";
		//根据access_token
		try {
			String url = "https://cx-service.westonecloud.com/api/apps/v1/access-tokens?app_key=" + appKey + "&corp_id=" + corpId + "&corp_secret=" + corpSecret;
			String r = HttpUtil.get(url);
 			JSONObject jobject = JSONObject.parseObject(r);
			String url2 = "https://cx-service.westonecloud.com/api/apps/v1/sso/user?access_token=" + jobject.getString("access_token") + "&oauth_code="+oauth_code;
			String r2 = HttpUtil.get(url2);
 			JSONObject jobject2 = JSONObject.parseObject(r2);
			 tele = jobject2.getString("mobile").substring(3);
		}catch (Exception ex ){
			logger.error(ex);
			throw new InvalidGrantException("调用卫士通接口失败！");
		}
		// 远程调用，获取认证信息
		R<UserInfo> result = userClient.userInfoByPhone(tenantId,tele);

		if (result.isSuccess()) {
			User user = result.getData().getUser();
			Kv detail = result.getData().getDetail();
			if (user == null) {
				throw new InvalidGrantException("卫士通授权登录失败，未找到该用户");
			}
			rapidUserDetails = new RapidUserDetails(user.getId(),
				tenantId, result.getData().getOauthId(), user.getName(), user.getRealName(), user.getDeptId(), user.getPostId(), user.getRoleId(), Func.join(result.getData().getRoles()),null,
				user.getName(), AuthConstant.ENCRYPT + user.getPassword(), detail, true, true, true, true,
				AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())));
		} else {
			throw new InvalidGrantException("westone grant failure, feign client return error");
		}


		Authentication userAuth = new UsernamePasswordAuthenticationToken(rapidUserDetails, null, rapidUserDetails.getAuthorities());
		((AbstractAuthenticationToken) userAuth).setDetails(parameters);
		OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);

		// 返回 OAuth2Authentication
		return new OAuth2Authentication(storedOAuth2Request, userAuth);
	}


}
